package com.example.myapplication;

import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import androidx.multidex.MultiDex;

import android.widget.Toast;

//import com.meituan.android.walle.WalleChannelReader;
//import com.example.myapplication.config.DynamicConfigImplDemo;
//import com.example.myapplication.listener.TestPluginListener;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.interfaces.BetaPatchListener;
//import com.tencent.matrix.Matrix;
//import com.tencent.matrix.iocanary.IOCanaryPlugin;
//import com.tencent.matrix.iocanary.config.IOConfig;
//import com.tencent.matrix.resource.ResourcePlugin;
//import com.tencent.matrix.resource.config.ResourceConfig;
//import com.tencent.matrix.trace.TracePlugin;
//import com.tencent.matrix.trace.config.TraceConfig;
//import com.tencent.matrix.util.MatrixLog;
//import com.tencent.sqlitelint.SQLiteLint;
//import com.tencent.sqlitelint.SQLiteLintPlugin;
//import com.tencent.sqlitelint.config.SQLiteLintConfig;
import com.tencent.tinker.entry.DefaultApplicationLike;

import java.util.Locale;

/**
 * 自定义ApplicationLike类.
 * <p>
 * 注意：这个类是Application的代理类，以前所有在Application的实现必须要全部拷贝到这里<br/>
 *
 * @author wenjiewu
 * @since 2016/11/7
 */
public class SampleApplicationLike extends DefaultApplicationLike {

    public static final String TAG = "Tinker.SampleApplicationLike";

    public SampleApplicationLike(Application application, int tinkerFlags,
                                 boolean tinkerLoadVerifyFlag, long applicationStartElapsedTime,
                                 long applicationStartMillisTime, Intent tinkerResultIntent) {
        super(application, tinkerFlags, tinkerLoadVerifyFlag, applicationStartElapsedTime,
                applicationStartMillisTime, tinkerResultIntent);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        // 设置是否开启热更新能力，默认为true
        Beta.enableHotfix = true;
        // 设置是否自动下载补丁，默认为true
        Beta.canAutoDownloadPatch = true;
        // 设置是否自动合成补丁，默认为true
        Beta.canAutoPatch = true;
        // 设置是否提示用户重启，默认为false
        Beta.canNotifyUserRestart = true;
        // 补丁回调接口
        Beta.betaPatchListener = new BetaPatchListener() {
            @Override
            public void onPatchReceived(String patchFile) {
                Toast.makeText(getApplication(), "补丁下载地址" + patchFile, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadReceived(long savedLength, long totalLength) {
                Toast.makeText(getApplication(),
                        String.format(Locale.getDefault(), "%s %d%%",
                                Beta.strNotificationDownloading,
                                (int) (totalLength == 0 ? 0 : savedLength * 100 / totalLength)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadSuccess(String msg) {
                Toast.makeText(getApplication(), "补丁下载成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDownloadFailure(String msg) {
                Toast.makeText(getApplication(), "补丁下载失败", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onApplySuccess(String msg) {
                Toast.makeText(getApplication(), "补丁应用成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onApplyFailure(String msg) {
                Toast.makeText(getApplication(), "补丁应用失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onPatchRollback() {

            }
        };

        // 设置开发设备，默认为false，上传补丁如果下发范围指定为“开发设备”，需要调用此接口来标识开发设备
        Bugly.setIsDevelopmentDevice(getApplication(), true);
        // 多渠道需求塞入
        // String channel = WalleChannelReader.getChannel(getApplication());
        // Bugly.setAppChannel(getApplication(), channel);
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId
        Bugly.init(getApplication(), "cab953ac58", true);
        OpenLogMethod();
//        InitMaterix();
//        InitMaterix2();
    }

//    private void InitMaterix2() {
//        Matrix.Builder builder = new Matrix.Builder(getApplication()); // build matrix
//        builder.patchListener(new TestPluginListener(getApplication())); // add general pluginListener
//        DynamicConfigImplDemo dynamicConfig = new DynamicConfigImplDemo(); // dynamic config
//
//        // init plugin
//        IOCanaryPlugin ioCanaryPlugin = new IOCanaryPlugin(new IOConfig.Builder()
//                .dynamicConfig(dynamicConfig)
//                .build());
//        //add to matrix
//        builder.plugin(ioCanaryPlugin);
//
//        //init matrix
//        Matrix.init(builder.build());
//
//        // start plugin
//        ioCanaryPlugin.start();
//    }

//    private void InitMaterix() {
//        DynamicConfigImplDemo dynamicConfig = new DynamicConfigImplDemo();
//        boolean matrixEnable = dynamicConfig.isMatrixEnable();
//        boolean fpsEnable = dynamicConfig.isFPSEnable();
//        boolean traceEnable = dynamicConfig.isTraceEnable();
//        MatrixLog.i(TAG, "MatrixApplication.onCreate");
//
//        Matrix.Builder builder = new Matrix.Builder(getApplication());
//        builder.patchListener(new TestPluginListener(getApplication()));
//
//        //trace
//        TraceConfig traceConfig = new TraceConfig.Builder()
//                .dynamicConfig(dynamicConfig)
//                .enableFPS(fpsEnable)
//                .enableEvilMethodTrace(traceEnable)
//                .enableAnrTrace(traceEnable)
//                .enableStartup(traceEnable)
//                .splashActivities("sample.tencent.matrix.SplashActivity;")
//                .isDebug(true)
//                .isDevEnv(false)
//                .build();
//
//        TracePlugin tracePlugin = (new TracePlugin(traceConfig));
//        builder.plugin(tracePlugin);
//
//        if (matrixEnable) {
//
//            //resource
//            Intent intent = new Intent();
//            ResourceConfig.DumpMode mode = ResourceConfig.DumpMode.MANUAL_DUMP;
//            MatrixLog.i(TAG, "Dump Activity Leak Mode=%s", mode);
//            intent.setClassName(getApplication().getPackageName(), "com.tencent.mm.ui.matrix.ManualDumpActivity");
//            ResourceConfig resourceConfig = new ResourceConfig.Builder()
//                    .dynamicConfig(dynamicConfig)
//                    .setAutoDumpHprofMode(mode)
////                .setDetectDebuger(true) //matrix test code
////                    .set(intent)
//                    .setManualDumpTargetActivity(KotlinActivity.class.getName())
//                    .build();
//            builder.plugin(new ResourcePlugin(resourceConfig));
//            ResourcePlugin.activityLeakFixer(getApplication());
//
//            //io
//            IOCanaryPlugin ioCanaryPlugin = new IOCanaryPlugin(new IOConfig.Builder()
//                    .dynamicConfig(dynamicConfig)
//                    .build());
//            builder.plugin(ioCanaryPlugin);
//
//
//            // prevent api 19 UnsatisfiedLinkError
//            //sqlite
//            SQLiteLintConfig sqlLiteConfig;
//            try {
//                sqlLiteConfig = new SQLiteLintConfig(SQLiteLint.SqlExecutionCallbackMode.CUSTOM_NOTIFY);
//            } catch (Throwable t) {
//                sqlLiteConfig = new SQLiteLintConfig(SQLiteLint.SqlExecutionCallbackMode.CUSTOM_NOTIFY);
//            }
//            builder.plugin(new SQLiteLintPlugin(sqlLiteConfig));
//
////            BatteryMonitorPlugin batteryMonitorPlugin = BatteryCanaryInitHelper.createMonitor();
////            builder.plugin(batteryMonitorPlugin);
//        }
//
//        Matrix.init(builder.build());
//
//        //start only startup tracer, close other tracer.
//        tracePlugin.start();
////        Matrix.with().getPluginByClass(BatteryMonitor.class).start();
//        MatrixLog.i("Matrix.HackCallback", "end:%s", System.currentTimeMillis());
//
//
//    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    public void onBaseContextAttached(Context base) {
        super.onBaseContextAttached(base);
        // you must install multiDex whatever tinker is installed!
        MultiDex.install(base);

        // TODO: 安装tinker
        Beta.installTinker(getApplication());
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void registerActivityLifecycleCallback(
            Application.ActivityLifecycleCallbacks callbacks) {
        getApplication().registerActivityLifecycleCallbacks(callbacks);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Beta.unInit();
    }


    /**
     * 方法描述: 开启日志记录方法
     * 创建人:  tangchao
     * 创建时间: 2017/10/23 12:37
     * 联系方式:419704299@qq.com
     */
    private void OpenLogMethod() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(0)         // (Optional) How many method line to show. Default 2
                .methodOffset(3)        // (Optional) Skips some method invokes in stack trace. Default 5
//        .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag("coroutines")   // (Optional) Custom tag for each log. Default PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));


    }
}
